import { dataSource } from "../../db/typeorm";
import { Menu } from "../../entity/menu";
import { formatPage, formatPageFileterData } from "../../utils/pages";
import { userRoleFindOne } from "../user/user";
import { MenuTree } from "./type";
import { menuArrayToTree } from "./utils";

// 获取菜单树
export async function menuTree({
  parent_id,
  user_id,
}: {
  parent_id?: number | string;
  user_id?: number | string;
}) {
  let querySql = dataSource.getRepository(Menu).createQueryBuilder();
  let dats: Menu[] = [];
  if (user_id && user_id !== 1) {
    // 根据用户过滤菜单
    const { menuIds } = await userRoleFindOne(Number(user_id));
    querySql = querySql.where("Menu.menu_id IN (:...menuIds)", { menuIds });
  }

  dats = await querySql.getMany();

  return menuArrayToTree(dats as unknown as MenuTree[]);
}

// 根据id获取菜单分页列表
export async function menuPageByParams(
  params: Menu & { pageIndex: number; pageSize: number },
  user_id?: string | number,
) {
  const { pageIndex, pageSize } = formatPage(params);
  const queryData = formatPageFileterData(params);
  if (!queryData.parent_id) {
    queryData.parent_id = 0;
  }

  let querySql = dataSource
    .getRepository(Menu)
    .createQueryBuilder()
    .where(queryData)
    .take(pageSize)
    .skip((pageIndex - 1) * pageSize);
  if (user_id && user_id !== 1) {
    const { menuIds } = await userRoleFindOne(Number(user_id));
    querySql = querySql.andWhere("menu.menu_id IN (:...menuIds)", { menuIds });
  }

  const records = await querySql.getMany(); // 获取查询结果
  const total = await querySql.getCount(); // 获取符合条件的数据总数

  return { total, records };
}

// 添加菜单
export async function menuAdd(menu: Menu) {
  const response = await dataSource
    .createQueryBuilder()
    .insert()
    .into(Menu)
    .values(menu)
    .execute();
  return response;
}

// 查询单个菜单详情
export async function menuFindOne(data: any) {
  return await dataSource.getRepository(Menu).findOneBy(data);
}

// 修改菜单
export async function menuUpdate(menu: Menu) {
  const result = await dataSource
    .createQueryBuilder()
    .insert()
    .update(Menu)
    .set(menu)
    .where("menu_id = :id", { id: menu.menu_id })
    .execute();
  return result;
}

// 根据ids [] 删除菜单
export async function menuDelByUserIds(ids: string[]) {
  await dataSource.getRepository(Menu).delete(ids);
}
